<template>
  <div>
    <div class="new_font1" >
      <div class="titleDiv"/>
      <div>
        产品信息
      </div>

    </div>
    <div>
      <div class="products_div3">
       <div>
          <span class="products_div2" v-for="(item,index) in products_number" :key="index">
          <span>
            {{item.label}}
          </span>
          <span class="products_font2">
            {{item.type == 2 ?Number(item.value).toFixed(2) : Number(item.value)}}
        </span>
        </span>
       </div>
        <div>
<!--          <el-button size="small" type="primary" @click="getMatch" :disabled="!getDisplay">匹配折扣赠品策略</el-button>-->
        </div>
      </div>
      <div>
        <el-form  :disabled="!getDisplay" ref="value_form" :model="productList" class="formData">
          <el-table
            row-key="id"
            border
            default-expand-all
            :data="productList"
            height="400px"

          >
            <el-table-column label="序号"  width="90" align="center">
              <template #default="props">
               {{props.row.serial_number}}
              </template>
            </el-table-column>
            <el-table-column prop="goods_type" align="center"  width="150">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  产品类型
                </span>
              </template>
              <template #default="props">
                <el-form-item prop="goods_type">
                  <VabSelectForm :disabled="props.row.association"  @change="goodsTypeChange($event,props.row.id,props.row)"  :clearable="false" v-if="goods_type_list.length >0"  v-model="props.row.goods_type" :options="goods_type_list"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="goods_no" align="center"  min-width="200">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  产品编码
                </span>
                <vab-icon
                  v-if="getDisplay"
                  icon="search-line"
                  style="color: #0967f4; margin-left: 12px"
                  @click="look_all"
                />
              </template>
              <template #default="props">
                <el-form-item prop="goods_no">
                  <PriceSelectLoading :disabled="props.row.association" v-if="props.row.goods_type != '赠品'&&props.row.goods_type != '样品'" :clearable="false" @change="goods_no_change($event,props.row.id,props.row)"  style="width: 100%" v-model="props.row.goods_no" type="number" :priceId="org_id"/>
                  <SelectLoading :disabled="props.row.association" :clearable="false" v-else @change="goods_no_change($event,props.row.id,props.row)" style="width: 100%" v-model="props.row.goods_no" type="number" :userOrgId="ol_id" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="goods_name" align="center" min-width="300">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  产品名称
                </span>
                <vab-icon
                  v-if="getDisplay"
                  icon="search-line"
                  style="color: #0967f4; margin-left: 12px"
                  @click="look_all"
                />
              </template>
              <template #default="props">
                <el-form-item prop="goods_name">
                  <PriceSelectLoading :disabled="props.row.association" :clearable="false" v-if="props.row.goods_type != '赠品'&&props.row.goods_type != '样品'" @change="goods_name_change($event,props.row.id,props.row)"  style="width: 100%" v-model="props.row.goods_name" type="name" :priceId="org_id"/>
                  <SelectLoading :disabled="props.row.association" :clearable="false" v-else @change="goods_name_change($event,props.row.id,props.row)" style="width: 100%" v-model="props.row.goods_name" type="" :userOrgId="ol_id" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="barcode" label="条码" align="center" width="130">
              <template #default="props">
                 <span
                   class="ellipsis"
                   v-text="_FieldFormat(props.row.barcode,  '')"
                 ></span>
              </template>
            </el-table-column>
            <el-table-column prop="spec_name" label="规格型号" align="center"  width="100">
            <template #default="props">
               <span
                 class="ellipsis"
                 v-text="_FieldFormat(props.row.spec_name,  '')"
               ></span>
            </template>
          </el-table-column>

            <el-table-column prop="sales_num" align="center"  width="150">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  销售数量
                </span>
              </template>
              <template #default="props">
                <el-form-item prop="sales_num">
                  <el-input-number :precision="0" @change="sales_num_change($event,props.row.id)" :controls='false' type="number" :min="0"   v-model.trim="props.row.sales_num" clearable class="input_many"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="warehouse_no" align="center" width="150">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  仓库
                  <span title="一键填充">
                  <vab-icon @click="warehouseFilling(productList)" class="downIcon" icon="down" is-custom-svg  />
                  </span>
                </span>
              </template>
              <template #default="props">
                <el-form-item prop="warehouse_no">
                  <el-select
                    filterable
                    v-model="props.row.warehouse_no"
                    class="width_100"
                    placeholder="请选择"
                    @change="valueName($event,props.row.id)"
                  >
                    <el-option v-for="item in warehouse_no_list" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="batch_usable_num" label="预计可发量" align="center" width="150">
              <template #header>
                <span>
                  预计可发量
<!--                    <vab-icon
                      v-if="getDisplay"
                      icon="search-line"
                      style="color: #0967f4; margin-left: 12px"
                    />-->
                </span>
              </template>
              <template #default="props">
                 <span class="ellipsis numberMoney">
                    {{_FieldFormat(props.row.batch_usable_num,  '')}}
               </span>
              </template>
            </el-table-column>
            <el-table-column prop="expire_date" label="效期备注" align="center" width="150">
              <template #default="props">
<!--                @change="valueName($event,props.row.id)"-->
                <el-form-item prop="expire_date">
                  <el-select
                    filterable
                    v-model="props.row.expire_date"
                    class="width_100"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option v-for="item in expire_date_list" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="batch_no" label="批次号备注" align="center" width="150">
              <template #default="props">
<!--                // @change="valueName($event,props.row.id)"-->
<!--                @focus="valueName($event,props.row.id)"-->
                <el-form-item prop="batch_no">
                  <el-select
                    filterable
                    v-model="props.row.batch_no"
                    class="width_100"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option v-for="item in props.row.batch_no_list" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价目表价格" align="center" width="150">
              <template #default="props">
                 <span class="ellipsis numberMoney">
                    ￥{{Number(props.row.price).toFixed(2) || 0.00 }}
               </span>
              </template>
            </el-table-column>
            <el-table-column prop="including_tax_price"  align="center" width="100">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  含税单价
                </span>
              </template>
              <template #default="props">
                 <span :class=" Number(props.row.including_tax_price) !== Number(props.row.price) ? 'fontSizeColor':''">
                <el-form-item prop="order_price" v-if = "props.row.goods_type=='正品'">
                  <el-input-number :precision="2" @change="order_price_change($event,props.row.id)" :controls='false' type="number" :min="0"  v-model.trim="props.row.including_tax_price" clearable class="input_many"/>
                </el-form-item>
                <span class="ellipsis numberMoney" v-if = "props.row.goods_type!='正品'">
                  {{Number(props.row.including_tax_price).toFixed(2) || 0.00}}
                </span>
                 </span>
              </template>
            </el-table-column>
            <el-table-column prop="price_remark" label="改价原因" align="center" width="150">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  改价原因
                </span>
              </template>
              <template #default="props">
                <el-form-item prop="remark">
                  <el-input v-model.trim="props.row.price_remark" :disabled=" Number(props.row.including_tax_price) === Number(props.row.price)|| props.row.goods_type !=='正品'"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="discount_rate" label="折扣率%" align="center" width="150">
              <template #default="props">
                <el-form-item prop="discount_rate">
                  <el-input-number v-model.trim="props.row.discount_rate" placeholder=" " type="number" :min="0" :max="100" :controls='false' class="input_many"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="tax_rate" label="税率" align="center" width="150">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  税率
                </span>
              </template>
              <template #default="props">
                <VabSelectForm  :clearable="false" v-if="tax_rate_list?.length >0"  @change="taxRateChange($event,props.row.id)"  v-model="props.row.tax_rate" :options="tax_rate_list"/>
              </template>
            </el-table-column>
            <el-table-column prop="total_amount" label="价税合计" align="center" width="150">
              <template #default="props">
                <span class="ellipsis numberMoney" >
                  ￥
                  {{Number(props.row.total_amount).toFixed(2) || 0.00}}
               </span>
              </template>
            </el-table-column>
            <el-table-column prop="sales_unit" align="center"  width="150">
              <template #header>
                <span class="spanFont">
                  *
                </span>
                <span>
                  销售单位
                </span>
              </template>
              <template #default="props">
                <span  class="ellipsis">
                    <el-form-item prop="sales_unit">
                  <VabSelectForm  :clearable="false" v-if="sales_unit_list?.length >0"  v-model="props.row.sales_unit" :options="sales_unit_list"/>
                </el-form-item>
               </span>
              </template>
            </el-table-column>
            <el-table-column prop="brand_name" label="品牌" align="center"  width="100">
              <template #default="props">
               <span  class="ellipsis">
                 {{_FieldFormat(props.row.brand_name,  '')}}
               </span>
              </template>
            </el-table-column>
            <el-table-column prop="order_price" label="不含税单价" align="center" width="150">
              <template #default="props">
                <span  class="ellipsis numberMoney">
                   ￥{{_FieldFormat(Number(props.row.order_price).toFixed(6),  '')}}
               </span>
              </template>
            </el-table-column>
            <el-table-column prop="tax" label="税额" align="center" width="100">
              <template #default="props">
                <span  class="ellipsis numberMoney">
                  {{_FieldFormat(Number(props.row.tax).toFixed(2),  '')}}
               </span>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="不含税金额" align="center" width="100">
              <template #default="props">
                <span  class="ellipsis numberMoney">
                  ￥
                    {{Number(props.row.amount).toFixed(2) || 0.00}}
               </span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="80">
              <template #header>
                <span>
                  操作
                </span>
                <vab-icon
                  icon="add-circle-line"
                  class="icon_color"
                  @click="handleClickAddHead"
                />
              </template>
              <template #default="props">
              <span v-if="!props.row.association">
                  <vab-icon
                    icon="add-circle-line"
                    class="icon_color"
                    @click="handleClickAdd(props.row)"
                  />
                <vab-icon
                  v-if="productList.length>1"
                  icon="delete-bin-5-line"
                  @click="handleClickRemove(props.row)"
                />
              </span>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </div>
    <ProductsAll ref="products_all" v-model:org_id="org_id" />
  </div>
</template>

<script setup lang="ts">
import {ref} from "vue";
import ProductsAll from './ProductsAll.vue'

defineOptions({
    name: 'ProductsInformation',
  })
const _FieldFormat = (value: string, type = '') => {
  return FieldFormat(value, type)
}
import { Search } from '@element-plus/icons-vue'
import {FieldFormat} from "/@/utils/utils";
import {getProductList, getProductSearch, productTaxRate} from "/@/api/dms/product";
import {ElMessage} from "element-plus";
import {getInventoryAvailable, getInventoryOrderSearch, getInventorySearchBatch} from "/@/api/dms/inventory";
import PriceSelectLoading from '/@/components/lazySelect/priceSelect.vue'
import SelectLoading from '/@/components/lazySelect/demo.vue'
import {customerPriceProductList, customerPriceProductSelect} from "/@/api/dms/customer";
import {orderMatch} from "/@/api/dms/order";
import {
  arr_giveaway,
  arr_map,
  convertToTree,
  filterateList,
  flattenArray,
  machList, productFields
} from "/@/views/order_management/orderText";
//客户   价目表
const props = defineProps(['copyProductList','copyProductNumber'])

//价目表
const org_id = ref<any>(undefined)
// 销售组织
const ol_id = ref<any>(undefined)
const getDisplay = ref(props.copyProductNumber && props.copyProductNumber.customer_uid != '' && props.copyProductNumber.price_list_uid != '' && props.copyProductNumber.sales_org_id != '')
const value_form = ref(null)
const name = ref([])
const number = ref([])
const formRef = ref(null)
const products_all =ref<any>(null)
const products_number = ref<any>([
  {label:'销售数量',item:'sales_num',value: props.copyProductNumber && props.copyProductNumber.sales_num || 0,type:'1'},
  {label:'计价数量',item:'pricing_num',value:props.copyProductNumber && props.copyProductNumber.pricing_num || 0,type:'1'},
  {label:'不含税金额',item:'amount',value:props.copyProductNumber && props.copyProductNumber.amount || 0.00,type:'2'},
  {label:'税额',item:'tax',value:props.copyProductNumber && props.copyProductNumber.tax || 0.00,type:'2'},
  {label:'价税合计',item:'total_amount',value:props.copyProductNumber && props.copyProductNumber.total_amount || 0.00,type:'2'},
  // {label:'折后金额',item:'discount_amount',value:props.copyProductNumber && props.copyProductNumber.discount_amount || 0.00,type:'2'},
])
const productList = ref<any>(props.copyProductList && convertToTree(props.copyProductList)  || [productFields])
// **********下拉框选项*****************
const goods_name_list = ref<any>([])
const goods_type_list = ref([{value:'正品',label:'正品'},{value:'赠品',label:'赠品'},{value:'样品',label:'样品'}])
const warehouse_no_list = ref([])
const expire_date_list  = ref([])
const tax_rate_list =  ref([])
const taxRate = ref<any>([])
// 销售单位
const sales_unit_list = ref([])
//*********仓库一键填充**************
const warehouseFilling = async (va:any)=>{
  const warehouseArray = flattenArray(va)
  const fillingOrder:any = warehouseArray.filter((i:any)=>i.goods_type !==''&& i.goods_no !== '' && i.goods_name !==''&& i.warehouse_no !=='')|| []
  if(fillingOrder.length >0){
    productList.value = convertToTree(await Promise.all( warehouseArray.map( async(item:any)=>{
        if(item.goods_type !==''&& item.goods_no !== '' && item.goods_name !==''&& item.warehouse_no ==''){
          let list:any = await getOrd(item.goods_no,fillingOrder[0]?.warehouse_no,item.batch_no,item.expire_date)
          return {
            ...item,
            warehouse_no:fillingOrder[0]?.warehouse_no,
            batch_usable_num:Number(list.available_num).toFixed(0),
          }
        }else {
          return item
        }
      })
    ))
  }
}
// ********添加产品*************
 const handleClickAdd =(row:any)=>{
   const newObject = {...productFields,id:String(new Date().getTime()).slice(-6)}
   const insertIndex = productList.value.findIndex((item:any)=> item.id === row.id) + 1;
   productList.value.splice(insertIndex, 0, newObject)
   // productList.value.push({id:String(new Date().getTime()).slice(-6),sales_num:0,goods_no:'',batch_usable_num:0,batch_no:'',expire_date:'',amount:0.00,goods_name:'',barcode:'',spec_name:'',brand_name:'',goods_type:'',sales_unit:'',sales_num:0,order_price:'',including_tax_price:0.00,tax_rate:'',tax:'',total_amount:0.00,warehouse_no:'',warehouse_name:'',stock_org_name:'',settle_org_name:'',remark:'',batch_no_list:[]})
   orderSort()
 }
 // 头部添加产品
const handleClickAddHead =()=>{
  const newObject = {...productFields,id:String(new Date().getTime()).slice(-6)}
  productList.value.splice(0, 0, newObject)
  orderSort()
}
 const handleClickRemove = (row:any)=>{
   productList.value =  productList.value.filter((item:any)=>item.id != row.id)

   orderSort()
 }
 // *******表格值变化*******
const goods_no_change = async (va:any,id:string|number,row:any)=>{
  const arr_list = [...productList.value]
  const arr =  await product_list(va,[],row)
  productList.value = arr_list.map((item:any)=>{
    if(item.id == id){
      const orderNumber:any = row.goods_type != '赠品'&& row.goods_type != '样品' ?(arr[0].price/(1+Number(arr[0].tax_rate )/100)).toFixed(6) : 0.000000
      return {
        ...item,
        sales_unit:arr[0].unit_name,// 销售单位
        goods_no:arr[0].number,//产品编码
        goods_name: arr[0].name,//产品名称
        barcode:arr[0].barcode || '',// 条码
        spec_name:arr[0].specification,//规格名称
        brand_name:arr[0].assistant_name,//品牌
        price:row.goods_type != '赠品'&& row.goods_type != '样品' ?arr[0].price:arr[0].retail_price , //价目表原始单价
        order_price:  orderNumber, //单价
        including_tax_price: row.goods_type != '赠品'&& row.goods_type != '样品' ? arr[0].price : 0.00, //含税单价
        tax_rate:arr[0].tax_rate, //税率
        tax:0.00, // 税额
        total_amount:0.00, //价税合计
        warehouse_no:'', //仓库编号
        warehouse_name:'', //仓库编号
        stock_org_name:'',//库存组织名称
        settle_org_name:'',//结算组织
        amount:0.00,// 金额
        sales_num:0,//销售数量
        batch_no:'',//批次号
        expire_date:'',//效期
        batch_usable_num:0,//预计可发量
        batch_no_list: arr[0].stock_batch?.map((i:any)=> {return {value:i.batch_no,label:i.batch_no}}),
        raw_data:arr[0],
        price_remark:'',
        children:[],//赠品策略
        discount_rate: row.goods_type == '正品'? 0 : 100,//折扣率
      }
    }else {
      return item
    }
  })
  countNumber(productList.value)
}
const goods_name_change= async (va:any,id:string|number,row:any)=>{
  if(row.goods_type == '赠品' || row.goods_type == '样品'){
    const arr_list = [...productList.value]
    const arr =  await product_list(va,[],row)
    productList.value = arr_list.map((item:any)=>{
      if(item.id == id){
        //retail_price
        const orderNumber:any = row.goods_type != '赠品'&& row.goods_type != '样品' ?(arr[0].price/(1+Number(arr[0].tax_rate )/100)).toFixed(6) : 0
        return {
          ...item,
          sales_unit:arr[0].unit_name,// 销售单位
          goods_no:arr[0].number,//产品编码
          goods_name: arr[0].name,//产品名称
          barcode:arr[0].barcode || '',// 条码
          spec_name:arr[0].specification,//规格名称
          brand_name:arr[0].assistant_name,//品牌
          order_price:  orderNumber, //单价
          price:row.goods_type != '赠品'&& row.goods_type != '样品' ?arr[0].price:arr[0].retail_price , //价目表原始单价
          including_tax_price:  row.goods_type != '赠品'&& row.goods_type != '样品'  ? arr[0].price : 0, //含税单价
          tax_rate:arr[0].tax_rate, //税率
          tax:0.00, // 税额
          total_amount:0.00, //价税合计
          warehouse_no:'', //仓库编号
          warehouse_name:'', //仓库编号
          stock_org_name:'',//库存组织名称
          settle_org_name:'',//结算组织
          amount:0.00,// 金额
          sales_num:0,//销售数量
          batch_no:'',//批次号
          expire_date:'',//效期
          batch_usable_num:0,//预计可发量
          batch_no_list: arr[0].stock_batch?.map((i:any)=> {return {value:i.batch_no,label:i.batch_no}}),
          raw_data:arr[0],
          price_remark:'',
          discount_rate: 100,//折扣率
        }
      }else {
        return item
      }
    })
  }else {
    const arr_list = [...productList.value]
    const arr =  await product_list([],va,row)
    productList.value = arr_list.map((item:any)=>{
      if(item.id == id){
        const orderNumber:any = row.goods_type != '赠品'&& row.goods_type != '样品' ?(arr[0].price/(1+Number(arr[0].tax_rate )/100)).toFixed(6) : 0
        return {
          ...item,
          sales_unit:arr[0].unit_name,// 销售单位
          goods_no:arr[0].number,//产品编码
          goods_name: arr[0].name,//产品名称
          barcode:arr[0].barcode || '',// 条码
          spec_name:arr[0].specification,//规格名称
          brand_name:arr[0].assistant_name,//品牌
          price:arr[0].price,//价目表原始单价
          order_price:  orderNumber, //单价
          including_tax_price: row.goods_type != '赠品' && row.goods_type != '样品' ? arr[0].price : 0, //含税单价
          tax_rate:arr[0].tax_rate, //税率
          tax:0.00, // 税额
          total_amount:0.00, //价税合计
          warehouse_no:'', //仓库编号
          warehouse_name:'', //仓库编号
          stock_org_name:'',//库存组织名称
          settle_org_name:'',//结算组织
          amount:0.00,// 金额
          sales_num:0,//销售数量
          batch_no:'',//批次号
          expire_date:'',//效期
          batch_usable_num:0,//预计可发量
          batch_no_list: arr[0].stock_batch?.map((i:any)=> {return {value:i.batch_no,label:i.batch_no}}),
          raw_data:arr[0],
          price_remark:'',
          children:[],//赠品策略
          discount_rate:0,//折扣率
        }
      }else {
        return item
      }
    })
  }

  countNumber(productList.value)
}
const valueName =async (value:string,id:string|number)=>{
  const arr_list = [...flattenArray(productList.value)]
  const arrId = arr_list.filter((i:any)=>i.id == id)[0]
  if(arrId.warehouse_no !== '' && arrId.warehouse_no !== undefined && arrId.warehouse_no!== null && arrId.goods_no !== '' && arrId.goods_no !== undefined && arrId.goods_no!== null){
    let list:any = await getOrd(arrId.goods_no,arrId.warehouse_no,arrId.batch_no,arrId.expire_date)
    let listNumber:any = await batchNoList(arrId.goods_no,arrId.warehouse_no,arrId.expire_date)
    let batch = listNumber?.find((i:any)=>i.value == arrId.batch_no)
    productList.value = convertToTree(arr_list.map((item:any)=>{
      if(item.id == id && item.goods_no!= ''&& item.warehouse_no!='' ){
        return {
          ...item,
          batch_usable_num:Number(list.available_num).toFixed(0),
         /* stock_org_name:list.stock_org?.organization_name,
          settle_org_name:list.settle_org?.organization_name,
          batch_no_list:listNumber,
          batch_no:batch && batch.value||'',*/
        }
      }else {
        return item
      }
    }))
  }

}
// 结算 列表总数据
const countNumber = (arr_list:any)=>{
  const pricing = arr_list.map((num:any)=> {if(num.goods_type !== '赠品'&& num.goods_type !== '样品'){return Number(num.sales_num) }else {return 0}} ).reduce((accumulator:any, currentValue:any) => accumulator + currentValue, 0)
  const total_amount = arr_list.map((num:any)=> Number( num.total_amount)).reduce((accumulator:any, currentValue:any) => accumulator + currentValue, 0)
  const amount = arr_list.map((num:any)=> Number( num.amount)).reduce((accumulator:any, currentValue:any) => accumulator + currentValue, 0)
  const taxList = arr_list.map((num:any)=> Number( num.tax)).reduce((accumulator:any, currentValue:any) => accumulator + currentValue, 0)
  const salesNumber = flattenArray(arr_list).map((i:any)=>i.sales_num).reduce((accumulator:any, currentValue:any) => Number(accumulator) + Number(currentValue), 0)
  // const salesNumber = arr_list.map((num:any)=> num.sales_num).reduce((accumulator:any, currentValue:any) => accumulator + currentValue, 0)
  products_number.value =  products_number.value.map((i:any)=>{
    if(i.item == 'sales_num'){
      return {
        ...i,
        value: Number(salesNumber),
      }
    }else if(i.item == 'pricing_num'){
      return {
        ...i,
        value:  isNaN(pricing) ? 0: Number(pricing)
      }
    }else if(i.item == 'total_amount'){
      return {
        ...i,
        value: Number(total_amount).toFixed(2)
      }
    } else if(i.item == 'amount'){
      return {
        ...i,
        value: Number(amount).toFixed(2)
      }
    } if(i.item == 'tax'){
      return {
        ...i,
        value: Number(taxList).toFixed(2)
      }
    }else {
      return  i
    }
  })
}
// 销售数量
const sales_num_change =  async (va:any,id:string|number)=>{
  const arr = productList.value.filter((i:any)=>i.id == id)
  const giveawayList = await machList(props.copyProductNumber,arr)
  // console.log(a )
  productList.value = productList.value.map((item:any)=>{
    if(item.id == id){
      const numb = Number(item.tax_rate)/100
      // 含税价
      const order:any =  (item.including_tax_price/(1+ numb)).toFixed(6) || 0.000000
      // 税额
      const taxNumber =  (order * numb * Number(va)).toFixed(2) || 0.00
      // 不含税金额
      const amountNumber = (order*va).toFixed(2) || 0.00
      // 含税金额
      const totalAmountNumber =  (item.including_tax_price * va ).toFixed(2)|| 0.00
      return {
        ...item,
        order_price:order,
        tax: taxNumber ,
        amount:amountNumber,
        total_amount:totalAmountNumber,
        children:[...giveawayList.map((item:any)=>{return{...item,association:true,discount_rate: 100,}})]
      }
    }else {
      return{
        ...item
      }
    }
  })
  countNumber(productList.value)
}
// 含税单价
const order_price_change =  (va:any,id:string|number)=>{
  const arr_list = [...productList.value]
  productList.value = arr_list.map((item:any)=>{
    if(item.id == id){
      const numb = Number(item.tax_rate)/100
      // 不含税价
      const order:any =(va/(1+ numb)).toFixed(6) || 0.000000
      // 税额
      const taxNumber =(order * numb * Number(item.sales_num || 0)).toFixed(2) || 0.00
      // 不含税金额
      const amountNumber =  ( order*Number(item.sales_num)).toFixed(2) || 0.00
      // 含税金额
      const totalAmountNumber =  ( Number(item.sales_num || 0) * va).toFixed(2) || 0.00
      return {
        ...item,
        tax: taxNumber,
        order_price:order,
        amount: amountNumber,
        total_amount:totalAmountNumber,
      }
    }else {
      return{
        ...item
      }
    }
  })
  countNumber(productList.value)
}
// 税率
const taxRateChange = (value:any,id:string|number)=>{
  const numb = Number(value)/100
 const   num = 1+ numb
  const arr_list = [...productList.value]
  productList.value = arr_list.map((item:any)=>{
    if(item.id == id){
      // 不含税价
      const order:any =  (item.including_tax_price/num).toFixed(6) || 0.000000
      // 税额
      const taxNumber = (order * numb * item.sales_num).toFixed(2) || 0.00
      // 不含税金额
      const amountNumber =  (order*item.sales_num).toFixed(2) || 0.00
      // 含税金额
      // const totalAmountNumber = va && va != 0 ?( Number(item.sales_num || 0) * va).toFixed(2) : 0.00
      return {
        ...item,
        tax: taxNumber,
        order_price:order,
        amount:amountNumber,
      }
    }else {
      return{
        ...item
      }
    }
  })
  countNumber(productList.value)
}
// 产品类型
const goodsTypeChange = (value:any,id:number|string,row:any)=>{
  const arr_list = [...productList.value]
  productList.value = arr_list.map((item:any)=>{
    if(item.id == id){
      return {
        ...item,
        children:[],
        sales_num:0,discount_rate: 0,goods_no:'',price:0.00,batch_usable_num:0,batch_no:'',expire_date:'',amount:0.00,goods_name:'',barcode:'',spec_name:'',brand_name:'',sales_unit:'',sales_num:0,order_price:'',including_tax_price:0.00,tax_rate:'',tax:'',total_amount:0.00,warehouse_no:'',warehouse_name:'',stock_org_name:'',settle_org_name:'',remark:'',batch_no_list:[]
      }
    }else {
      return{
        ...item
      }
    }
  })
  countNumber(productList.value)
}

// 查看全部产品
const look_all = ()=>{
  products_all.value.dialogVisibles = true
}
const product_list = async (number_list:any,name_list:any,row:any)=>{
  if(row.goods_type == '赠品' || row.goods_type == '样品'){
    let arr = await getProductList({page:1,limit:500,type:1,filter:{number:number_list || [],name:name_list || [],use_org_id: props.copyProductNumber && props.copyProductNumber.sales_org_id}})
    return arr.data.list
  }else {
    let arr = await customerPriceProductList({page:1,limit:2000,id:org_id.value,filter:{number:number_list || [],name:name_list || []}})
    return arr.data.list
  }
}

// 获取产品 名称  编码
const all_date = ref<any>([])
// 通过产品id 仓库名称 获取销售组织 结算组织
const getOrd= async (uid:number|string,ownerId:number|string,batchId='',expireId='')=>{
  if(uid != ''&& ownerId !== '' ){
    let arr:any = await getInventoryAvailable({spec_no:uid,owner_no:ownerId,batch_no:batchId,expire_day:expireId})
    return arr.data
  }else {
    return {}
  }
}
//动态获取批次号
const batchNoList = async (spec_no:number|string,owner_no:number|string,expire_day:number|string,)=>{
  if(spec_no !='' && spec_no){
    let arr = await getInventorySearchBatch({spec_no:spec_no,owner_no:owner_no,expire_day:expire_day})
    return arr.data.list.map((i:any)=> {return {value:i.batch_no,label:i.batch_no}})
  }else {
    return {}
  }
}
// 获取基础数据
const _GetProductSearch = async () => {
  try {
    const res = await getProductSearch()
    const tax = await productTaxRate({})
    res.data.brand.push({ entry_id: '', name: '空' })
    res.data.class_one.push({ id: '', data_title: '空' })
    res.data.class_two.push({ id: '', data_title: '空' })
    res.data.series.push({ id: '', data_title: '空' })
    res.data.category.push({ id: '', data_title: '空' })
    all_date.value = res.data
    taxRate.value = tax.data
  } catch (error) { }
}
//赠品策略匹配
const getMatch = ()=>{
  if(filterateList(productList.value).length>0){
    orderMatch({...props.copyProductNumber,detail:[...filterateList(productList.value)]}).then((data:any)=>{
      if(data.code == 200 ){
        if( data.data?.item_list.length>0){
          const arrNumber =  data.data?.item_list.map((item:any)=>{return item.goods_no})
          getProductList({page:1,limit:20,type:1,filter:{number:arrNumber,use_org_id:props.copyProductNumber.sales_org_id}}).then((item:any)=>{
            if(item.code == 200){
              productList.value = [...filterateList(productList.value),...arr_giveaway(item.data.list,data.data?.item_list)]
              ElMessage.success(`匹配成功`)
            }
          })
        }else {
          ElMessage.warning(`该订单产品无赠品策略`)
        }
      }
    })
  }else {
    ElMessage.warning(`产品信息不准为空`)
  }
}
// 序号排序
const orderSort = ()=>{
  // 订单列表排序
  productList.value = productList.value.map((value:any,index:any)=>{
    if(value.children){
      return{
        ...value,
        serial_number:index +1,
        children:value.children.map((item:any,i:any)=>{
          return{
            ...item,
            serial_number:index+1+'.'+ (i + 1)
          }
        })
      }
    }else {
      return{
        ...value,
        serial_number:index +1

      }
    }

  })
}
onMounted(()=>{
  _GetProductSearch()
})
watchEffect(()=>{
  const { multipleList } = products_all.value || []
  if( multipleList ){
    const arr = [...multipleList]
    productList.value = [...filterateList(productList.value),...arr_map(arr)]
    products_all.value.multipleList = undefined
    countNumber(productList.value)
  }
  tax_rate_list.value = taxRate.value.tax_rate?.map((i:any)=> {return {value:i.tax_rate,label:i.rate_name}})
  sales_unit_list.value = taxRate.value.unit?.map((i:any)=> {return {value:i.name,label:i.name}})
  warehouse_no_list.value = taxRate.value.wms_owner?.map((i:any)=> {return {value:i.owner_no,label:i.short_name}})
  expire_date_list.value = taxRate.value.expire_list?.map((i:any)=> {return {value:String(i.day),label:i.name}})
  getDisplay.value = props.copyProductNumber && props.copyProductNumber.customer_uid != '' && props.copyProductNumber.price_list_uid != '' && props.copyProductNumber.sales_org_id != ''
  // 获取组织uid  customerPriceProductSelect
  org_id.value = props.copyProductNumber && props.copyProductNumber.price_list_uid || undefined
  // 获取组织uid  customerPriceProductSelect
  ol_id.value = props.copyProductNumber && props.copyProductNumber.sales_org_id || undefined

  countNumber(productList.value)
//排序
  orderSort()


})
//抛出数据
defineExpose({
  productList,
  products_number,
})
</script>

<style lang="scss" scoped>
@import "../index";
.products_font1{
  font-size: 16px;
  margin-bottom: 15px;
}
.products_div{
  width: 300px;
}
.products_div1{
  margin-right: 20px;
  margin-left: 10px;
  display:inline-block;
  :deep(){
    .el-input__wrapper{
      border-bottom-right-radius: 0px !important;
      border-top-right-radius: 0px !important;
      border-right: 0px solid !important;
    }
    .el-button{
      border-bottom-left-radius: 0px !important;
      border-top-left-radius: 0px !important;
      border-left: 0px solid !important;
    }
  }
}
.products_font2{
 color: rgb(245, 154, 35);
  margin-left: 20px;
}
.products_div2{
  margin-right: 20px;
}
.products_div3{
  display: flex;
  justify-content: space-between;
  margin-bottom: 25px;
  margin-top: 25px;
}
.formData {
  :deep() {
    .el-form-item {
      margin-bottom: 0px;
    }
  }
  .icon_color {
    color: #0967f4;
    margin-right: 4px;
  }
}
</style>

